package com.shunhao.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import butterknife.ButterKnife
import butterknife.Unbinder
import com.UserManagerCenter.isLogin
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.components.ImmersionFragment
import com.shunhao.model.EventCenter
import com.shunhao.widgets.dialog.ProgressDialogUtil
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *类作用描述:    基类Fragment 基于Kotlin
 *@author      KangGuiYang
 *创建时间      2020/6/15 13:37
 *邮箱        kangguiyang2@gmail.com
 *公司        南京舜贝佳信息科技 Shunbega.com
 *
 */
abstract class BaseFragment : ImmersionFragment() {

    protected var mContext: Context? = null
    private var isFirstResume: Boolean = true
    private var isFirstVisible: Boolean = true
    private var isFirstInvisible: Boolean = true
    private var isPrepared: Boolean = false
    lateinit var mRootView: View

    private val compositeDisposable: CompositeDisposable = CompositeDisposable()

    // 黄油刀 考虑要不要去掉
    private var mUnBinder: Unbinder? = null

    private var savedInstanceState: Bundle? = null

    // 初始化状态栏
    override fun initImmersionBar() {

    }

    // eventBus回调
    // eventCenter 回调对象
    protected abstract fun onEventComing(eventCenter: EventCenter<Any>)

    // 设置Fragment ui 页面 xml 布局id
    protected abstract fun getContentViewLayoutId(): Int

    // 这是当前Fragment是否注册EventBus
    protected abstract fun isBindEventBusHere(): Boolean

    // 懒加载用 第一次用户页面可见
    protected abstract fun onFirstUserVisible()

    // 用户可见 类似于 onResume
    protected abstract fun onUserVisible()

    //第一次用户不可见 不操作
    private fun onFirstUserInvisible() {}

    // 当用户不可见时(onPause)
    protected abstract fun onUserInvisible()

    //初始化布局以及监听事件
    protected abstract fun initViews()

    // 初始化业务操作
    protected abstract fun initData()

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 判断是否注册EventBus
        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 根View 赋值
        mRootView = view
        mUnBinder = ButterKnife.bind(this, mRootView)
        this.savedInstanceState = savedInstanceState
        initViews()
        initData()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return if (getContentViewLayoutId() != 0) {
            // 设置Fragment布局
            val layoutId = getContentViewLayoutId()
            inflater.inflate(layoutId, null)
        } else {
            super.onCreateView(inflater, container, savedInstanceState)
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initPrepare()
    }

    @Synchronized
    private fun initPrepare() {
        if (isPrepared) {
            onFirstUserVisible()
        } else {
            isPrepared = true
        }
    }

    override fun onResume() {
        super.onResume()
        if (isFirstResume) {
            isFirstResume = false
            return
        }
        if (userVisibleHint) {
            onUserVisible()
        }
    }

    override fun onPause() {
        super.onPause()
        if (userVisibleHint) {
            onUserInvisible()
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false
                initPrepare()
            } else {
                onUserVisible()
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false
                onFirstUserInvisible()
            } else {
                onUserInvisible()
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (isBindEventBusHere()) {
            EventBus.getDefault().unregister(this)
        }
        mUnBinder?.unbind()

        // 解除RxJava2的订阅
        if (!compositeDisposable.isDisposed) {
            compositeDisposable.dispose()
        }
    }


    /**
     * 用户是否登录
     * @return 用户是否登录
     */
    fun isUserLogin(): Boolean {
        return isLogin()
    }


    fun addCompositeDisposable(disposable: Disposable) {
        compositeDisposable.add(disposable)
    }

    fun stopCompositeDisposable(disposable: Disposable) {
        if (!disposable.isDisposed) {
            disposable.dispose()
        }
    }

    protected open fun showToast(message: String) {
        ToastUtils.showShort(message)
    }

    protected open fun showToast(msgId: Int) {
        ToastUtils.showShort(msgId)
    }

    protected open fun readyGo(clazz: Class<*>?) {
        val intent = Intent(activity, clazz)
        startActivity(intent)
    }

    protected open fun readyGo(clazz: Class<*>?, bundle: Bundle?) {
        val intent = Intent(activity, clazz)
        if (null != bundle) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    protected open fun readyGoForResult(clazz: Class<*>?, requestCode: Int) {
        val intent = Intent(activity, clazz)
        startActivityForResult(intent, requestCode)
    }

    protected open fun readyGoForResult(
        clazz: Class<*>?,
        requestCode: Int,
        bundle: Bundle?
    ) {
        val intent = Intent(activity, clazz)
        if (null != bundle) {
            intent.putExtras(bundle)
        }
        startActivityForResult(intent, requestCode)
    }


    /**
     * EventBus回调
     * @param eventCenter 消息对象
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventMainThread(eventCenter: EventCenter<Any>?) {
        eventCenter?.let { onEventComing(it) }
    }

    /***
     * 发送EventBus消息
     * @param code 发送code
     */
    open fun sentEventByEventBus(code: Int) {
        EventBus.getDefault().post(EventCenter<Any>(code))
    }

    /**
     * 发送EventBus消息
     *
     * @param code 发送code
     * @param obj  传递消息对象
     */
    open fun sentEventByEventBusWithBundle(code: Int, obj: Any?) {
        if (obj == null) {
            sentEventByEventBus(code)
            return
        }
        EventBus.getDefault().post(EventCenter(code, obj))
    }

    /**
     * 展示loading框
     */
    open fun showLoading() {
        ProgressDialogUtil.getInstance().showProgressDialog(mContext, true)
    }

    /**
     * 展示loading框 自定义文本
     *
     * @param message 自定义文本内容
     */
    open fun showLoadingWithText(message: String?) {
        ProgressDialogUtil.getInstance().showProgressDialogMsg(message, mContext, true)
    }

    /**
     * 关闭loading框
     */
    open fun hideLoading() {
        ProgressDialogUtil.getInstance().closeProgressDialog()
    }

}